package com.zhengshang.api.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.pdd.pop.sdk.common.util.JsonUtil;
import com.pdd.pop.sdk.http.PopClient;
import com.pdd.pop.sdk.http.PopHttpClient;
import com.pdd.pop.sdk.http.api.pop.request.PddDdkResourceUrlGenRequest;
import com.pdd.pop.sdk.http.api.pop.response.PddDdkResourceUrlGenResponse;
import com.zhengshang.api.domain.*;
import com.zhengshang.api.service.*;
import com.zhengshang.common.annotation.RepeatSubmit;
import com.zhengshang.common.constant.app.AppConstant;
import com.zhengshang.common.constant.app.ShoppingConstant;
import com.zhengshang.common.core.controller.BaseController;
import com.zhengshang.common.core.domain.AjaxResult;
import com.zhengshang.common.core.domain.entity.SysDictData;
import com.zhengshang.common.core.domain.entity.SysUser;
import com.zhengshang.common.core.domain.model.LoginAppUser;
import com.zhengshang.common.utils.DateUtils;
import com.zhengshang.common.utils.DictUtils;
import com.zhengshang.common.utils.StringUtils;
import com.zhengshang.common.utils.http.HttpUtils;
import com.zhengshang.common.utils.sign.SignMD5Util;
import com.zhengshang.security.service.TokenService;
import com.zhengshang.system.service.ISysConfigService;
import com.zhengshang.system.service.ISysDictDataService;
import com.zhengshang.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * 首页Controller
 *
 * @author zhengshang
 * @date 2021-03-09
 */
@Api(tags = "首页")
@RestController
@RequestMapping("/home")
public class HomeController extends BaseController {
    @Autowired
    private IAppBannerService appBannerService;
    @Autowired
    private IAppNavigateService appNavigateService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IAppVersionService appVersionService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IAppVideoService appVideoService;
    @Autowired
    private IAppVideoDramaService appVideoDramaService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IAppBillRecordService appBillRecordService;

    @Autowired
    private ISysDictDataService sysDictDataService;

    /**
     * 获取banner图列表
     */
    @ApiOperation(value = "获取轮播图列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "bannerType", value = "轮播图类型（1首页banner，2个人中心banner，3商品banner(暂时不用)，4分享海报,5:游戏，6 逛一逛）", dataType = "String", paramType = "query")
    })
    @GetMapping("/bannerList")
    public AjaxResult bannerList(
            @RequestParam String bannerType) {
        if (StringUtils.isBlank(bannerType)) {
            return AjaxResult.error("参数不正确");
        }
        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType("app_banner_type");
        List<SysDictData> sysDictDataList = sysDictDataService.selectDictDataList(sysDictData);
        List<String> bannerTypes = Lists.newArrayList();
        sysDictDataList.forEach(sysDictData1 -> {
            String dictValue = sysDictData1.getDictValue();
            bannerTypes.add(dictValue);
        });
        if (!bannerTypes.contains(bannerType)) {
            return AjaxResult.error("请输入正确的轮播图类型");
        }
        AppBanner appBanner = new AppBanner();
        appBanner.setBannerStatus("1");
        appBanner.setBannerType(bannerType);
        List<AppBanner> list = appBannerService.queryAppBannerList(appBanner);
        String ossBaseUrl = configService.selectConfigByKey("sys.oss.file.header");
        for (AppBanner banner : list) {
            banner.setImgUrl(ossBaseUrl + banner.getImgUrl());
        }
        return AjaxResult.success(list);
    }


    /**
     * 获取星级会员充值活动标记
     */
    @ApiOperation(value = "获取星级会员充值活动标记")
    @GetMapping("/getActivity")
    public AjaxResult getActivity(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        Integer tag = 0;
        //是否开启星级会员充值活动
        String activity = configService.selectConfigByKey("app.manmber.activity");
        LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
        Long userId = loginAppUser.getAppUser().getUserId();
        SysUser user = userService.selectUserById(userId);
        String appMemberType = user.getAppMemberType();
        if (ObjectUtils.isNotEmpty(activity) && activity.equals("1") && appMemberType.equals("2")) {
            tag = 1;
            if (appMemberType.equals("2")) {
                //检测特殊商品充值
                AppBillRecord appBillRecord = new AppBillRecord();
                appBillRecord.setUserId(userId);
                appBillRecord.setRemark("110");
                String date = DateUtils.getMonth();
                appBillRecord.setSearchValue(date);
                List<AppBillRecord> appBillRecordList = appBillRecordService.queryAppBillRecordList(appBillRecord);
                if (ObjectUtils.isNotEmpty(appBillRecordList)) {
                    tag = 0;
                }
            }
        }
        result.put("activity", tag);
        return AjaxResult.success(result);
    }

    /**
     * 获取话费充值URL
     */
    @PreAuthorize("@ss.hasPermi('app:phoneBill:recharge')")
    @ApiOperation(value = "获取话费充值URL")
    @GetMapping("/phoneBillRecharge")
    public AjaxResult phoneBillRecharge(
            HttpServletRequest request, HttpServletResponse response) {

//        try {
//            LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("uid", loginAppUser.getAppUser().getUserId());
//            PopClient client = new PopHttpClient(ShoppingConstant.PDD_CLIENT_ID, ShoppingConstant.PDD_CLIENT_SECRET);
//
//            PddDdkResourceUrlGenRequest requestPDD = new PddDdkResourceUrlGenRequest();
//            requestPDD.setCustomParameters(jsonObject.toJSONString());
//            requestPDD.setGenerateWeApp(true);
//            requestPDD.setPid(ShoppingConstant.PDD_PID);
//            requestPDD.setResourceType(ShoppingConstant.PDD_RESOURCE_TYPE_RECHARGE);
//            PddDdkResourceUrlGenResponse responsePDD = client.syncInvoke(requestPDD);
//            System.out.println(JsonUtil.transferToJson(responsePDD));
//            return AjaxResult.success("获取成功", JSONObject.parseObject(JsonUtil.transferToJson(responsePDD)));
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return AjaxResult.error("获取失败");
        String rechargeUrl = configService.selectConfigByKey("app.phone.bill.recharge.url");
        return AjaxResult.success("获取成功", rechargeUrl);
    }

    /**
     * 获取购买视频会员URL
     */
    @PreAuthorize("@ss.hasPermi('app:video:all')")
    @ApiOperation(value = "获取购买视频会员URL")
    @GetMapping("/buyVideoMember")
    public AjaxResult buyVideoMember(
            HttpServletRequest request, HttpServletResponse response) {
        String buyVideoUrl = configService.selectConfigByKey("app.buy.video.member.url");
        return AjaxResult.success("获取成功", buyVideoUrl);
    }

    @ApiOperation("获取移动端二维码")
    @GetMapping({"/getQrcodeUrl"})
    public AjaxResult getQrcodeUrl(HttpServletRequest request, HttpServletResponse response) {
        String ossBaseUrl = this.configService.selectConfigByKey("sys.oss.file.header");
        String domainUrl = this.configService.selectConfigByKey("sys.domain.name");

        String[] types = {"1", "2"};
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < types.length; i++) {
            AppVersion appVersion = new AppVersion();
            appVersion.setVersionType(types[i]);
            AppVersion app = this.appVersionService.getNewAppVersion(appVersion);
            JSONObject object = new JSONObject();
            if ("1".equals(appVersion.getVersionType())) {
                object.put("fileUrl", ossBaseUrl + app.getFilesUrl());
            } else if ("2".equals(app.getVersionType())) {
                object.put("fileUrl", app.getFilesUrl());
            }
            object.put("versionType", app.getVersionType());
            object.put("url", ossBaseUrl + app.getQrCodeUrl());
            jsonArray.add(object);
        }
        return AjaxResult.success("获取成功", jsonArray);
    }

    @ApiOperation(value = "获取视频列表")
    @PreAuthorize("@ss.hasPermi('app:video:all')")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "videoName", value = "视频名", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "videoType", value = "视频类型", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pageNum", value = "页码（从1开始）", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数（最小为1，最大为100）", required = false, dataType = "int", paramType = "query")
    })
    @PostMapping("/getVideoList")
    public AjaxResult getVideoList(
            @RequestParam(required = false) String videoName,
            @RequestParam(required = false) String videoType,
            @RequestParam Integer pageNum,
            @RequestParam(required = false) Integer pageSize,
            HttpServletRequest request, HttpServletResponse response) {

        if (pageNum == null || pageNum.intValue() <= 0 || (pageSize != null && pageSize.intValue() < 1)) {
            return AjaxResult.error("参数错误");
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        if (pageSize.intValue() > 100) {
            pageSize = 100;
        }
        try {

            AppVideo appVideo = new AppVideo();
            appVideo.setVideoClass("1");
            if (StringUtils.isNotBlank(videoName)) {
                appVideo.setVideoName(videoName);
            }
            if (StringUtils.isNotBlank(videoType)) {
                appVideo.setVideoType(videoType);
            }
            appVideo.getParams().put("pageNum", pageNum);
            appVideo.getParams().put("pageSize", pageSize);

            String ossBaseUrl = configService.selectConfigByKey("sys.oss.file.header");
            String hasHeaderUrl = configService.selectConfigByKey("sys.oss.has.video.header");
            List<AppVideo> appVideoList = appVideoService.queryAppVideoList(appVideo);
            for (AppVideo video : appVideoList) {
                if ((StringUtils.isNotBlank(video.getVideoUrl())) && ("1".equals(hasHeaderUrl))) {
                    video.setVideoUrl(ossBaseUrl + video.getVideoUrl());
                }
                if (StringUtils.isNotBlank(video.getVideoThumbnailImg())) {
                    video.setVideoThumbnailImg(ossBaseUrl + video.getVideoThumbnailImg());
                }
            }
            return AjaxResult.success(appVideoList);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("<home.getVideoList>获取视频列表：{}", e.getMessage());
            return AjaxResult.error("获取视频列表，请联系管理员");
        }
    }

    @ApiOperation(value = "获取电视剧剧集")
    @PreAuthorize("@ss.hasPermi('app:video:all')")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "videoId", value = "电视剧ID", required = false, dataType = "Long", paramType = "query"),
    })
    @PostMapping("/getTVPlay")
    public AjaxResult getVideoList(
            @RequestParam Long videoId,
            HttpServletRequest request, HttpServletResponse response) {

        try {

            if (videoId == null || videoId.longValue() <= 0) {
                return AjaxResult.error("参数错误");
            }
            String ossBaseUrl = configService.selectConfigByKey("sys.oss.file.header");
            List<AppVideoDrama> appVideoDramaList = appVideoDramaService.queryAppVideoDramaListByVideoId(videoId);
            for (AppVideoDrama appVideoDrama : appVideoDramaList) {
                appVideoDrama.setDramaUrl(ossBaseUrl + appVideoDrama.getDramaUrl());
            }
            return AjaxResult.success("查询成功", appVideoDramaList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error("查询失败");
    }

    @ApiOperation(value = "获取视频类型")
    @PreAuthorize("@ss.hasPermi('app:video:all')")
    @PostMapping("/getVideoType")
    public AjaxResult getVideoType(
            HttpServletRequest request, HttpServletResponse response) {

        try {

            JSONArray jsonArray = DictUtils.getDictJSONCache("app_video_type");
            if (jsonArray != null) {
                return AjaxResult.success("查询成功", jsonArray);
            }
            logger.error("<home.getVideoType>视频类型数据为空");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error("查询失败");
    }

    @ApiOperation(value = "获取在线学习视频列表")
    @PreAuthorize("@ss.hasPermi('app:education:all')")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "videoName", value = "视频名", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "videoType", value = "视频类型", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pageNum", value = "页码（从1开始）", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数（最小为1，最大为100）", required = false, dataType = "int", paramType = "query")
    })
    @PostMapping("/getEducationVideoList")
    public AjaxResult getEducationVideoList(
            @RequestParam(required = false) String videoName,
            @RequestParam(required = false) String videoType,
            @RequestParam Integer pageNum,
            @RequestParam(required = false) Integer pageSize,
            HttpServletRequest request, HttpServletResponse response) {

        if (pageNum == null || pageNum.intValue() <= 0 || (pageSize != null && pageSize.intValue() < 1)) {
            return AjaxResult.error("参数错误");
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        if (pageSize.intValue() > 100) {
            pageSize = 100;
        }
        try {

            AppVideo appVideo = new AppVideo();
            appVideo.setVideoClass("2");
            if (StringUtils.isNotBlank(videoName)) {
                appVideo.setVideoName(videoName);
            }
            if (StringUtils.isNotBlank(videoType)) {
                appVideo.setVideoType(videoType);
            }
            appVideo.getParams().put("pageNum", pageNum);
            appVideo.getParams().put("pageSize", pageSize);

            String ossBaseUrl = configService.selectConfigByKey("sys.oss.file.header");
            List<AppVideo> appVideoList = appVideoService.queryAppVideoList(appVideo);
            for (AppVideo video : appVideoList) {

//                if (StringUtils.isNotBlank(video.getVideoUrl())) {
//                    video.setVideoUrl(ossBaseUrl + video.getVideoUrl());
//                }
                if (StringUtils.isNotBlank(video.getVideoThumbnailImg())) {
                    video.setVideoThumbnailImg(ossBaseUrl + video.getVideoThumbnailImg());
                }
            }
            return AjaxResult.success(appVideoList);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("<home.getEducationVideoList>获取在线学习视频列表：{}", e.getMessage());
            return AjaxResult.error("获取在线学习视频列表，请联系管理员");
        }
    }

    @ApiOperation(value = "获取在线教育类型")
    @PreAuthorize("@ss.hasPermi('app:education:all')")
    @PostMapping("/getEducationType")
    public AjaxResult getEducationType(
            HttpServletRequest request, HttpServletResponse response) {

        try {

            JSONArray jsonArray = DictUtils.getDictJSONCache("app_education_type");
            if (jsonArray != null) {
                return AjaxResult.success("查询成功", jsonArray);
            }
            logger.error("<home.getEducationType>在线教育类型数据为空");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error("查询失败");
    }

    @ApiOperation("获取配置信息")
    @PostMapping("/getConfig")
    public AjaxResult getConfig(HttpServletRequest request, HttpServletResponse response) {
        try {

            JSONObject jsonObject = new JSONObject();

            //开屏广告
            jsonObject.put("openscreen", configService.selectConfigByKey("app.config.openscreen"));

            //福利社
            jsonObject.put("openWelfare", configService.selectConfigByKey("app.config.advertisement.welfare"));

            //客服电话
            String telephone = configService.selectConfigByKey("app.customer.telephone");
            jsonObject.put("telephone", telephone);

            //提现规则
            String withdrawalRules = configService.selectConfigByKey("app.withdrawal.rules");
            withdrawalRules = withdrawalRules.replace("<telephone>", telephone);
            jsonObject.put("withdrawalRules", withdrawalRules);
            return AjaxResult.success("查询成功", jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error("查询失败");
    }

    @ApiOperation("获取提现配置信息")
    @GetMapping("/getWithdrawalFeeConfig")
    public AjaxResult getWithdrawalFeeConfig() {
        try {
            JSONObject jsonObject = new JSONObject();
            //提现费率
            String withdrawalFeeStr = configService.selectConfigByKey("app.withdrawal.fee");
            BigDecimal withdrawalFee = new BigDecimal(withdrawalFeeStr).divide(new BigDecimal(100));
            jsonObject.put("withdrawalFee", withdrawalFee);
            return AjaxResult.success("查询成功", jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error("查询失败");
    }

    @ApiOperation("获取最新版本信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "versionType", value = "版本类型（1=Android，2=IOS）", required = false, dataType = "String", paramType = "query"),
    })
    @PostMapping("/getVersion")
    public AjaxResult getVersion(@RequestParam String versionType, HttpServletRequest request, HttpServletResponse response) {
        try {
            if ((StringUtils.isBlank(versionType)) || ((!"1".equals(versionType)) && (!"2".equals(versionType)))) {
                return AjaxResult.error("参数错误");
            }

            AppVersion appVersionQuery = new AppVersion();
            appVersionQuery.setVersionType(versionType);
            AppVersion appVersion = appVersionService.getNewAppVersion(appVersionQuery);
            if ("1".equals(versionType)) {
                appVersion.setFilesUrl(configService.selectConfigByKey("sys.oss.file.header") + appVersion.getFilesUrl());
            }
            return AjaxResult.success("查询成功", appVersion);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error("查询失败");
    }


    /**
     * 获取app首页导航列表
     */
    @ApiOperation(value = "获取app首页导航列表")
    @GetMapping("/navigateList")
    public AjaxResult navigateList() {
        AppNavigate appNavigate = new AppNavigate();
        appNavigate.setNavigateStatus("1");
        List<AppNavigate> list = appNavigateService.queryAppNavigateList(appNavigate);
        String ossBaseUrl = configService.selectConfigByKey("sys.oss.file.header");
        for (AppNavigate navigate : list) {
            navigate.setNavigateIcon(ossBaseUrl + navigate.getNavigateIcon());
        }
        return AjaxResult.success(list);
    }

}
